<?php

namespace App\Models\Ncdh;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class NcdhOrderDetailLog extends Model
{
    protected $table = "game_ncdh_order_detail_log";

    const
        UNPAY_NO = 0,   //正常
        UNPAY_YES = 1;  //撤销

    /**
     * 获取用户某期购买数据总和，按投注类型合计
     * @param $issue
     * @param $userId
     *
     * @return array
     */
    public static function getUserOrderDetailSumByType($issue, $userId)
    {
        $orderDetailItems = self::getUserOrderDetail($issue, $userId);

        return self::getOrderDetailSumByType($orderDetailItems);
    }

    /**
     * 获取用户某期的下单详情
     * @param $issue
     * @param $userId
     *
     * @return mixed
     */
    public static function getUserOrderDetail($issue, $userId)
    {
        return self::where('issue', $issue)->where('user_id', $userId)->where('unpay', self::UNPAY_NO)->orderBy('id', 'DESC')->get()->toArray();
    }

    /**
     * 获取某期下单详情
     * @param $issue
     *
     * @return mixed
     */
    public static function getOrderDetail($issue)
    {
        return self::where('issue', $issue)->where('unpay', self::UNPAY_NO)->orderBy('id', 'DESC')->get()->toArray();
    }

    /**
     * 按类型归类下单总额
     * @param $orderDetailItems
     * @return array
     */
    public static function getOrderDetailSumByType($orderDetailItems)
    {
        //获取所有下单种类
       $sort=config('ncdh.pay_type');
        
        //初始化各个种类金额
        $sumInfo = [];
        foreach ($sort as $key=>$sortValue) {
            $sumInfo[$key] = 0;
        }

        foreach ($orderDetailItems as $item) {

            if (!isset($sumInfo[$item['type']])) {
                $sumInfo[$item['type']] = 0;
            }

            $sumInfo[$item['type']] += $item['gold'];
        }
        return $sumInfo;
    }

    /**
     * 每个用户某期购买总额
     * @param $issue
     * @param $userId
     *
     * @return int
     */
    public static function getUserPayGoldPerIssue($issue, $userId)
    {
        $payGold = self::where('issue', $issue)
            ->where('user_id', $userId)
            ->where('unpay', self::UNPAY_NO)
            ->sum('gold');

        if (empty($payGold)) {
            return 0;
        }

        return $payGold;
    }

    /**
     * 更新某期订单详情中奖标记
     * @param $issue
     * @param $winType
     *
     * @return mixed
     */
    public static function updateWinType($issue, $winType)
    {

        $number = NcdhOrderDetailLog::where('issue', $issue)
            ->where('unpay', 0)
            ->whereIn('type', $winType)
            ->update([
                'is_win' => 1,
                'update_time' => time(),
            ]);


        return $number;
    }

    /**
     * 获取最近中奖详情（用户昵称、中奖类型、中奖金额）
     */
    public static function getLatestWinDetail($size = 30)
    {

        if (empty($size)) {
            $size = 30;
        }

        $winList = DB::select('select * from ( select user_id, issue, type, sum(gold) gold from game_sgdzz_order_detail_log where is_win = 1 and unpay = 0 group by user_id,issue order by issue desc limit ?) tmp group by user_id order by issue desc limit ?', [max(300, min(100, $size * 10)), $size]);
        $winList = json_decode(json_encode($winList), true);

        $userIds = array_column($winList, 'user_id');

        if (!empty($userIds)) {
            $listArr = User::whereIn('id', $userIds)->select('id', 'avatar', 'nickname')->get()->toArray();
            $listArrByUserId = [];
            foreach ($listArr as $item) {
                $listArrByUserId[$item['id']] = $item;
            }

            foreach ($winList as $key => $winItem) {
                $winList[$key]['nickname'] = $listArrByUserId[$winItem['user_id']]['nickname'];
                $winList[$key]['avatar'] = $listArrByUserId[$winItem['user_id']]['avatar'];
                $winList[$key]['gold'] = $winItem['gold'] * config('ncdh.award_times');
            }
        }

        return $winList;
    }

    /**
     * 获取用户当期中奖金额
     * @param $issue
     * @param $userId
     *
     * @return mixed
     */
    public static function getUserWinGold($issue, $userId, $winType)
    {

        $winTypeArray = explode(",", $winType);

        $payGold = self::select('gold','type')
            ->where('issue', $issue)->where('user_id', $userId)->whereIn('type', $winTypeArray)->where('unpay', self::UNPAY_NO)
            ->get()->toArray();
       
        if (empty($payGold)) {
            return 0;
        }

        return $payGold * config('ncdh.award_times');

    }

    /**
     * 按类型归类每个用户的下单总额
     * @param $orderDetailItems
     *
     * @return array
     */
    public static function getOrderDetailSumByTypeUserId($orderDetailItems)
    {
        $sumInfo = [];
        foreach ($orderDetailItems as $item) {
            if (!isset($sumInfo[$item['type']])) {
                $sumInfo[$item['type']] = [];
            }
            if (!isset($sumInfo[$item['type']][$item['user_id']])) {
                $sumInfo[$item['type']][$item['user_id']] = 0;
            }
            
            $sumInfo[$item['type']][$item['user_id']] += $item['gold'];
        }

        return $sumInfo;
    }
}
